package com.mingmen.canting.zhenbanlibrary;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.canting.R;
import com.mingmen.canting.adapter.MyLabelAdapter;
import com.mingmen.canting.base.BaseBean;
import com.mingmen.canting.defineview.PayPassDialog;
import com.mingmen.canting.defineview.PayPassView;
import com.mingmen.canting.dialog.ButtomDialogView;
import com.mingmen.canting.http.callback.StringCallback;
import com.mingmen.canting.httpconfig.HttpResponse;
import com.mingmen.canting.model.CommdityColletModel;
import com.mingmen.canting.model.GetMarkModel;
import com.mingmen.canting.model.ShopListModel;
import com.mingmen.canting.util.GsonUtil;
import com.mingmen.canting.util.SharePreferenceUtil;
import com.mingmen.canting.util.ToolList;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

@SuppressLint("ValidFragment")
public class CollectFragment extends Fragment implements CollectAdapter.OnItemClickListener, CompoundButton.OnCheckedChangeListener {
    @BindView(R.id.card_title_tv)
    TextView cardTitleTv;
    @BindView(R.id.recycle_collect)
    RecyclerView recycleCollect;
    @BindView(R.id.layout_nodata)
    LinearLayout layoutNodata;
    Unbinder unbinder;
    private String mTitle;
    //Fragment的View加载完毕的标记
    private boolean isLoading = false;

    //Fragment对用户可见的标记
    private boolean isUIVisible;

    public static CollectFragment getInstance(String title) {
        CollectFragment sf = new CollectFragment();
        sf.mTitle = title;
        return sf;
    }

    private CollectAdapter mAdapter;
    List<ShopListModel.DataBean> myLiveList = new ArrayList<>();
    String token;
    List<String> applyList = new ArrayList<>();
    @BindView(R.id.tv_total)
    TextView tv_total;
    @BindView(R.id.cb_check)
    CheckBox cb_check;
    int myflag = 0;
    int select_shop = 0;
    @BindView(R.id.btn_submit)
    Button btn_submit;
    @BindView(R.id.layout_selectall)
    LinearLayout layout_selectall;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_collect, null);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);
        unbinder = ButterKnife.bind(this, v);
//        EventBus.getDefault().register(this);
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        recycleCollect.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new CollectAdapter(getActivity(), myLiveList);
        recycleCollect.setAdapter(mAdapter);
        token = (String) SharePreferenceUtil.get(getActivity(), "token", "");
        mAdapter.setOnItemClickListener(this);
        refreshData();
        cb_check.setOnCheckedChangeListener(this);
        return v;
    }


    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

    public void refreshData() {
        HttpResponse.getQuickCommodityList(token, "1", "1", new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("getQuickCommodityList", s);
                if (myLiveList.size() > 0) {
                    myLiveList.clear();
                }
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    ShopListModel shopListModel = new ShopListModel();
                    shopListModel = GsonUtil.GsonToBean(s, ShopListModel.class);
                    myLiveList.addAll(shopListModel.getData());
                    if (myLiveList.size() == 0) {
                        recycleCollect.setVisibility(View.GONE);
                        layoutNodata.setVisibility(View.VISIBLE);
                        layout_selectall.setVisibility(View.GONE);
                    } else {
                        recycleCollect.setVisibility(View.VISIBLE);
                        layoutNodata.setVisibility(View.GONE);
                        layout_selectall.setVisibility(View.VISIBLE);
                    }


                    mAdapter.setDataList(myLiveList);
                }


            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.card_title_tv, R.id.recycle_collect, R.id.layout_nodata, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.card_title_tv:
                break;
            case R.id.recycle_collect:
                break;
            case R.id.layout_nodata:
                break;

            case R.id.btn_submit:
                if (applyList.size() == 0) {
                    Toast.makeText(getActivity(), "请选择商品数量", Toast.LENGTH_SHORT).show();
                } else {
//                    Toast.makeText(mContext, "成功", Toast.LENGTH_SHORT).show();
                    String submitDate = (String) SharePreferenceUtil.get(getActivity(), "submitDate", "");
                    Log.d("submitDate", submitDate);
                    submitData(submitDate);

                }
                break;
        }
    }

    public void onEventMainThread(Integer integer) {
        if (integer == 20) {
            cb_check.setChecked(false);
            refreshData();
        }

    }

    /*    @Override
        public void onItemClickListener1(View view, int pos, List<ShopListModel.DataBean> myLiveList) {

            switch (view.getId()) {
                case R.id.img_collect:
                    getCollect(token, pos, myLiveList.get(pos).getCommodityId(), myLiveList);
                    break;

            }

        }*/
    @Override
    public void onItemClickListener1(View view, int pos, List<ShopListModel.DataBean> myLiveList) {
        switch (view.getId()) {
            case R.id.checkbox:
            case R.id.layout_checkbox:
                if (myLiveList.get(pos).getApplyAmount() == 0) {
                    Toast.makeText(getActivity(), "请选择商品数量", Toast.LENGTH_SHORT).show();
                    myLiveList.get(pos).setChecked(false);
                    mAdapter.notifyDataSetChanged();
                } else {
                    for (ShopListModel.DataBean cart : myLiveList) {
                        if (cart.isChecked()) {   //是否勾上去了

                            Log.d("勾选上了", "勾选上了");
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("commodityId", cart.getCommodityId());
                                jsonObject.put("commodityAmount", cart.getApplyAmount() + "");
                                jsonObject.put("categoryId", "0");
                                jsonObject.put("mark", cart.getMark());
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            applyList.add(jsonObject.toString());
                            ToolList.removeDuplicateWithOrder(applyList);
                            tv_total.setText("已选购" + applyList.size() + "");

                            Log.d("applyListapplyListapplyList", applyList.toString());

                            myflag = 0;
                            if (myLiveList.size() == applyList.size()) {
                                cb_check.setChecked(true);
                            }
                            Log.d("datasize", myLiveList.size() + "");
                            Log.d("applyList", applyList.size() + "");


                        } else {
                            Log.d("取消勾选", "取消勾选");
                            myflag = 1;
                            cb_check.setChecked(false);
                            if (applyList.size() > 0) {
                                for (int i = 0; i < applyList.size(); i++) {
                                    if (applyList.get(i).contains(cart.getCommodityId())) {
                                        applyList.remove(i);
                                    }
                                }

                            } else if (applyList.isEmpty()) {

                            } else if (applyList.size() == 0) {

                            }

                            ToolList.removeDuplicateWithOrder(applyList);
                            Log.d("applyListapply", applyList.toString());
                            tv_total.setText("已选购" + applyList.size() + "");


                        }
                    }
                }

                break;
            case R.id.img_add:
            case R.id.tv_add:
            case R.id.tv_reduce:
                select_shop = myLiveList.get(pos).getApplyAmount();
                break;
            case R.id.text_beizhu:

                createPopwindow(pos, myLiveList);

                break;
            case R.id.img_collect:

                getCollect(token, pos, myLiveList.get(pos).getCommodityId(), myLiveList);

                break;

            case R.id.tv_num:
                payDialog3(pos, myLiveList);
                break;

        }
    }


    public void getCollect(String token, int pos, String commodityId, List<ShopListModel.DataBean> myLiveList) {
        HttpResponse.setCommodityCollect(token, commodityId, new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                Log.d("setCommodityCollect", s);
                BaseBean baseBean = new BaseBean();
                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    CommdityColletModel commdityColletModel = GsonUtil.GsonToBean(s, CommdityColletModel.class);
                    myLiveList.get(pos).setCollectionFlag(commdityColletModel.getData().getData());
                    mAdapter.notifyDataSetChanged();
                    EventBus.getDefault().post(21);
                    refreshData();
                    Toast.makeText(getActivity(), commdityColletModel.getMessage(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    public void createPopwindow(int pos, List<ShopListModel.DataBean> myLiveList) {
        MyLabelAdapter myLabelAdapter;
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());

        View view1 = layoutInflater.inflate(R.layout.dialog_bottom, null);

        ButtomDialogView bottomSheetDialog = new ButtomDialogView(getActivity(), view1, true, true);
        bottomSheetDialog.setContentView(R.layout.toast_dialog);
        bottomSheetDialog.show();
        RecyclerView recycle_biaoqian = view1.findViewById(R.id.recycle_biaoqian);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        recycle_biaoqian.setLayoutManager(gridLayoutManager);
        EditText verify_et = view1.findViewById(R.id.verify_et);

        TextView text_submit = view1.findViewById(R.id.text_submit);
        myLabelAdapter = new MyLabelAdapter(getActivity());
        recycle_biaoqian.setAdapter(myLabelAdapter);
        List<String> mystr = new ArrayList<>();

        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.custom_divider));
        recycle_biaoqian.addItemDecoration(divider);
        ImageView img_close = view1.findViewById(R.id.img_close);
        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.dismiss();
            }
        });

        HttpResponse.getMark(token, "4", new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("getMarkgetMark", s);

                GetMarkModel getMarkModel = new GetMarkModel();
                getMarkModel = GsonUtil.GsonToBean(s, GetMarkModel.class);
                for (int i = 0; i < getMarkModel.getData().size(); i++) {
                    mystr.add(getMarkModel.getData().get(i).getMark());
                    myLabelAdapter.setDataList(mystr);
                }

                myLabelAdapter.setOnItemClickListener(new MyLabelAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClickListener(View view, int pos, List<String> myLiveList) {
                        Log.d("ZHenBanMYsortDetail", myLiveList.get(pos));
                        myLabelAdapter.setCheckedPosition(pos);
                        verify_et.setText(myLiveList.get(pos));
                    }
                });
            }
        });

        text_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myLiveList.get(pos).setMark(verify_et.getText().toString());
                bottomSheetDialog.dismiss();
                mAdapter.notifyDataSetChanged();
            }
        });

    }

    /**
     * 3 自定义方式
     */
    private void payDialog3(int pos, List<ShopListModel.DataBean> myLiveList) {
        final PayPassDialog dialog = new PayPassDialog(getActivity(), R.style.dialog_pay_theme);
        //弹框自定义配置
        dialog.setAlertDialog(false)
                .setWindowSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.4f)
                .setOutColse(false) //点击外部是否消失
                .setGravity(R.style.dialogOpenAnimation, Gravity.BOTTOM);
        //组合控件自定义配置
        dialog.getPayViewPass()
                .setHintText("数量")
                .setForgetText("密码忘记?")
                .setForgetColor(getResources().getColor(R.color.colorAccent))
                .setForgetSize(16)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String password) {
                        //6位输入完成回调
//                        Toast.makeText(mContext, "输入内容:" + password, Toast.LENGTH_SHORT).show();
                        Log.d("passwordpassword", password);

                        if (password.equals("")) {

                        } else {
                            Integer int_count = Integer.valueOf(password);
                            myLiveList.get(pos).setApplyAmount(int_count);
                            mAdapter.notifyDataSetChanged();
                        }


                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭回调
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();

                    }
                });
    }

    public void submitData(String submitDate) {

//        submitDate
        HttpResponse.submitData(token, submitDate, "1", applyList.toString(), "8点之前", new StringCallback(getActivity()) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Log.d("SortDetailFragment", s);
                BaseBean baseBean = new BaseBean();

                baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
                    EventBus.getDefault().post(11);
                    EventBus.getDefault().post(31);
                    EventBus.getDefault().post(30);
                    getActivity().finish();
                }
                Toast.makeText(getActivity(), baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            int flag = 0;
            myflag = 0;
            Log.d("applyListapplyList", applyList.toString());
            for (int i = 0; i < myLiveList.size(); i++) {
                if (myLiveList.get(i).getApplyAmount() > 0) {
                    flag = myLiveList.get(i).getApplyAmount();
                }
            }
            if (flag == 0) {
                Toast.makeText(getActivity(), "请选择商品数量", Toast.LENGTH_SHORT).show();
                cb_check.setChecked(false);
            } else {
                for (int i = 0; i < myLiveList.size(); i++) {
                    if (myLiveList.get(i).getApplyAmount() > 0) {
                        cb_check.setChecked(true);
                        myLiveList.get(i).setChecked(true);

                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("commodityId", myLiveList.get(i).getCommodityId());
                            jsonObject.put("commodityAmount", myLiveList.get(i).getApplyAmount() + "");
                            jsonObject.put("categoryId", "0");
                            jsonObject.put("mark", myLiveList.get(i).getMark());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        applyList.add(jsonObject.toString());
                        ToolList.removeDuplicateWithOrder(applyList);


                    } else {
                        myLiveList.get(i).setChecked(false);
                    }

                }
            }

            Log.d("AllSelectAllApplist", applyList.toString());
//                        showTotalPrice();
            tv_total.setText("已选购" + applyList.size() + "");
            mAdapter.notifyDataSetChanged();
        } else {
            if (myflag == 0) {
                for (int i = 0; i < myLiveList.size(); i++) {
                    myLiveList.get(i).setChecked(false);
                }
                applyList.clear();
                mAdapter.notifyDataSetChanged();
                Log.d("NoSelectAllApplist", applyList.toString());
                tv_total.setText("已选购" + applyList.size() + "");

            } else {

            }

        }
    }
}